package com.epam.education.bilyi.shopingcart;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ShopingCartImpl implements ShopingCart {

	private final static String ERROR_MESSAGE_QUANTITY = "quantity parameter less than 1.";
	private final static String ERROR_MESSAGE_EMPTY_SHOPING_CART = "shoping cart is empty.";
	private final static String ERROR_MESSAGE_GOODS_IS_NOT_EXIST = "goods is not exist."; 
	
	private Map<Goods, Integer> goodsMap;
	private int allGoodsCount;
	private BigDecimal totalPrice;
	
	public ShopingCartImpl() {
		goodsMap = new HashMap<Goods, Integer>();
		totalPrice = new BigDecimal(0);
	}
	
	public void addGoods(Goods goods) {
		addGoods(goods, 1);
	}

	public void addGoods(Goods goods, int quantity) {
		if (quantity < 1) {
			throw new IllegalArgumentException(ERROR_MESSAGE_QUANTITY);
		}
		
		goodsMap.put(goods, goodsMap.get(goods) == null ? quantity : goodsMap.get(goods) + quantity);
		
		BigDecimal priceGoods = goods.getPrice().multiply(new BigDecimal(quantity));
		totalPrice = totalPrice.add(priceGoods);
		
		allGoodsCount += quantity;
	}

	public void deleteGoods(Goods goods) {
		if (allGoodsCount < 1) {
			throw new ShopingCartException(ERROR_MESSAGE_EMPTY_SHOPING_CART);
		}
	
		Integer goodsCount = goodsMap.get(goods); 
		if (goodsCount != null) {
			if (goodsCount == 1) {
				goodsMap.remove(goods);
			} else {
				goodsMap.put(goods, goodsCount - 1);
			}
			allGoodsCount--;
			totalPrice = totalPrice.subtract(goods.getPrice());
		} else {
			throw new ShopingCartException(ERROR_MESSAGE_GOODS_IS_NOT_EXIST);
		}
	}

	public int getCoodsCount() {
		return allGoodsCount;
	}

	public List<Goods> getGoodsList() {
		return new ArrayList<Goods>(goodsMap.keySet());
	}

	public BigDecimal getTotalSum() {
		return totalPrice;
	}

}
